#include <iostream>
#include <string>
#include <websocketpp/config/asio_client.hpp>
#include <websocketpp/client.hpp>
#include <websocketpp/common/thread.hpp>

typedef websocketpp::client<websocketpp::config::asio_client> client;
using websocketpp::lib::bind;
using websocketpp::lib::error_code;
using websocketpp::lib::ref;
using websocketpp::lib::thread;

void _recv(client &c, websocketpp::connection_hdl hdl, client::message_ptr msg)
{
    std::cout << "client-recv: " << msg->get_payload() << std::endl;
}

int main(int argc, char const *argv[])
{
    client c;
    c.set_access_channels(websocketpp::log::alevel::none);
    c.set_message_handler(bind(&_recv, ref(c), std::placeholders::_1, std::placeholders::_2));

    c.init_asio();
    c.start_perpetual();

    error_code e;
    auto conn = c.get_connection("ws://127.0.0.1:9002", e);
    c.connect(conn);
    // auto conn2 = c.get_connection("ws://127.0.0.1:9002", e);
    // c.connect(conn2);

    thread t(&client::run, &c);
    std::string msg;
    std::cout << "client start, press ctrl+D to quit!" << std::endl;
    while (std::cin >> msg)
    {
        std::cout << "client-send: " << msg << std::endl;
        c.send(conn->get_handle(), msg, websocketpp::frame::opcode::text);
    }
    std::cout << "client stop!" << std::endl;
    c.stop_perpetual();
    c.stop();
    t.join();

    return 0;
}
